<script setup>
import { ref, onMounted, reactive } from "vue"
import { generateSign2, ossImg, ObjectToQueryString } from "@/utils/utils";
import { userLogin } from "@/services/utils"
import { debounce } from "lodash";
import { onHide, onShareAppMessage, onUnload } from "@dcloudio/uni-app";
import { ShareConfig } from "./config";
import { QRCODE_BASE_URI } from "@/campaign/pages/cloudsample/config";
import GoBuyDialog from "./components/GoBuyDialog.vue";
import ResultDialog from "./components/ResultDialog.vue";

const codeValue = ref('')
const emdlz = getApp().emdlz
const state = reactive({
  resultCode: 400,
  resultDialogVisible: false,
  buyModalVisible: false
})
const locationInfo = ref({ latitude: "", longitude: "" })
let enterTime = "";
let outTime = "";
let stayTime = "";

onShareAppMessage(() => ShareConfig())

onMounted(() => {
  // 用户进入时间
  enterTime = new Date();
  getApp().accessLogAdd();
})

const afterPhoneValidate = () => {
  return new Promise((resolve, reject) => {
    if (!getApp().globalData.user.phone) {
      uni.navigateTo({ url: "/pages/vip/register?tag=scanCode" });
      reject()
    }
    resolve()
  })
}

const uploadStayTimeEvent = (evt) => {
  console.log('---------stayTimeEvt', evt)
  if (!enterTime) return
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  console.log('----------stayTime', stayTime)
  emdlz('track','event','Oreo_eggy_redeem_page','view','eggy_redeem_page', stayTime);
}

onUnload(() => uploadStayTimeEvent('onBeforeMount'))
onHide(() => uploadStayTimeEvent('hide'))

// 生成兑奖H5需要参数
const getWebviewSearchParams = (body) => ObjectToQueryString({
  // 'accesstoken': uni.getStorageSync("TOKEN"),
  'code': body.qrCode || '',
  // 'openid': uni.getStorageSync("OPENID"),
  // 'unionid': uni.getStorageSync("UNIONID"),
  // 'memberid': body?.memberScore?.memberId || getApp().globalData?.user?.memberScore?.memberId || '',
  // 'agree': 'true'
})

// 点击确认按钮
const onSubmit = debounce(async () => {
  emdlz('track','event','Oreo_eggy_redeem_page','click','update_code','');
//   if (!codeValue.value) return uni.showToast({ title: '字符串为空', icon: 'none' })
//   await afterPhoneValidate()
//   uni.getLocation({
//     type: "gcj02",
//     success(res) {
//       locationInfo.value.latitude = res.latitude;
//       locationInfo.value.longitude = res.longitude;
//     },
//     async complete() {
//       const body = {
//         userValue: uni.getStorageSync("OPENID"),
//         qrCode: codeValue.value,
//         source: "Q4",
//         timestamp: Date.parse(new Date()),
//         lng: locationInfo.value.longitude,
//         lat: locationInfo.value.latitude,
//       }
//       // 没有获取到OPENID
//       if (!body.userValue) {
//         try {
//           console.log({ ...body })
//           await getApp().getUserLoginInfo()
//           const user = await getApp().getUserInfo()
//           linkTo(`/campaign/pages/cloudsample/webview?${getWebviewSearchParams({ ...body, ...user })}`);
//         } catch (e) {
//           uni.showToast({ title: '服务器响应错误', icon: 'none' })
//         }
//         return
//       }
//       uni.showLoading({ title: '正在查询', mask: true });
//       uni.request({
//         url: `${QRCODE_BASE_URI}/zex-qr/api/qr/validation`,
//         method: "get",
//         data: {
//           ...body,
//           ...{ sign: generateSign2(body) },
//         },
//         success: (result) => {
//           uni.hideLoading();
//           codeValue.value = ""
//           // 码正确处理
//           if (result.data.code === 200) {
//             // 静默拿取微信用户的 openId 与 unionId 信息
//             uni.login({
//               provider: "weixin",
//               success: async (loginResult) => {
//                 const loginParam = { type: 1, code: loginResult.code };
//                 const { data } = await userLogin(loginParam);
//                 uni.setStorageSync("TOKEN", data?.accessToken);
//                 uni.setStorageSync("OPENID", data?.openId);
//                 uni.setStorageSync("UNIONID", data?.unionId);
//                 getApp().emdlz("set", "user", "openid", data?.openId);
//                 getApp().emdlz("set", "user", "unionId", data?.unionId);
//                 // 兑奖H5
//                 linkTo(`/campaign/pages/cloudsample/webview?${getWebviewSearchParams(body)}`);
//               },
//             });
//             return
//           }
//           // 接口报错
//           if (!result?.data.code) return linkTo(`/campaign/pages/cloudsample/status?status=2`);
//           // 码错误处理
//           state.resultCode = result?.data?.code === 4000 ? 400 : result?.data?.code
//           console.log('码错误处理', state.resultCode)
//           state.resultDialogVisible = true
//         },
//         fail: requestErr => {
//           uni.hideLoading();
//           uni.showToast({
//             title: requestErr.data.message,
//             icon: "none",
//             duration: 2000,
//           });
//         }
//       })
//     },
//   })
// }, 500, {
//   leading: true,
//   trailing: false,
  return linkTo(`/campaign/pages/cloudsample/status?status=1`);
})

const linkTo = url => uni.navigateTo({ url })
const backPrevPage = () => {
  emdlz('track','event','Oreo_eggy_redeem_page','click','go_back','');
  uni.navigateBack()
}

const onClickInput = () => {
  emdlz('track','event','Oreo_eggy_redeem_page','click','add_code1','');
}

const handleChangeModalStatus = status => {
  console.log('我的console？？？')
  state.resultCode = status
  state.resultDialogVisible = true
}
</script>

<template>
  <view
    class="main-content box-border pb-39px"
    :style="{ backgroundImage: `url(${ossImg('others/cloudsample/color_bg.png')})`,}"
  >
    <image
      class="w-72px h-26px block absolute top-47px left-0 py-10px"
      :src="ossImg('others/cloudsample/but_back.png')"
      @click.stop="backPrevPage"
    ></image>
<!--    <view class="test-menu">-->
<!--      <view @click.stop="handleChangeModalStatus(4000)">打开码异常弹窗</view>-->
<!--      <view @click.stop="handleChangeModalStatus(4002)">打开码已核销弹窗</view>-->
<!--      <view @click.stop="handleChangeModalStatus(4001)">打开码未激活</view>-->
<!--      <view @click.stop="handleChangeModalStatus(400)">打开字符串有误弹窗</view>-->
<!--      <view @click.stop="handleChangeModalStatus('err')">打开微信扫码提示</view>-->
<!--    </view>-->
    <image
      class="w-375px h-506px mb-5px"
      :src="ossImg('others/cloudsample/verifcation_title_min.png')"
    ></image>
    <!--  核销数据框  -->
    <view class="code-input mb-23px">
      <image class="input-bg" :src="ossImg('others/cloudsample/sr_input.png')"></image>
      <image class="edit-icon" :src="ossImg('others/cloudsample/edit_icon.png')"></image>
      <input
        v-model="codeValue"
        placeholder-style="color: #6E6E6E;"
        placeholder="请输入字符串"
        @click.stop="onClickInput"
      />
    </view>
    <!--  按钮组  -->
    <image
      class="w-158px h-56px"
      :src="ossImg('others/cloudsample/but_sure.png')"
      @click.stop="onSubmit"
    ></image>
    <!--  结果弹窗  -->
    <result-dialog
      v-if="state.resultDialogVisible"
      :result-code="state.resultCode"
      @close="state.resultDialogVisible = false"
    ></result-dialog>
    <!--  去购买弹窗  -->
    <go-buy-dialog
      v-if="state.buyModalVisible"
      @close="state.buyModalVisible = false"
    ></go-buy-dialog>
  </view>
</template>

<style lang="less" scoped>
@import "@/static/css/theme.less";

.test-menu {
  position: fixed;
  background-color: white;
  top: 10px;
  right: 0;
  padding: 10px;
  view {
    margin: 2px 0;
  }
}

image {
  display: block;
}

.code-input {
  display: flex;
  width: 290px;
  height: 55px;
  position: relative;
  align-items: center;
  box-sizing: border-box;
  padding-left: 29px;
  .input-bg {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
  }
  .edit-icon {
    position: absolute;
    width: 26px;
    height: 24px;
    right: 28px;
  }
  input {
    width: 204px;
    height: 25px;
    background: #FFFFFF;
    border-radius: 3px;
    padding: 0 8px 0 8px;
    box-sizing: border-box;
    font-size: 15px;
    position: relative;
    z-index: 8;
  }
}

.main-content {
  width: 100%;
  min-height: 100vh;
  background-color: #0DB4FD;
  background-position: top left;
  background-size: 375px 748px;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
}
.fixed-btn__group {
  flex-direction: column;
  align-items: flex-end;
  .fixed-btn {
    width: 36px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    margin-bottom: 14px;
    text {
      color: white;
      font-size: 9px;
      margin-top: 3px;
      line-height: 1;
    }
  }
}
.text-line {
  color: white;
  display: flex;
  align-items: center;
  font-size: 11px;
  & > image {
    margin-right: 6px;
  }
  text {
    text-decoration: underline;
  }
}
.result-modal {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  &::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, .6);
    z-index: -1;
  }
  .dialog-body {
    width: 311px;
    height: 324px;
    position: relative;
    margin-top: -56px;
    .result-image {
      width: 100%;
      height: 100%;
    }
    .close-icon {
      width: 25px;
      height: 25px;
      position: absolute;
      top: 68px;
      right: 28px;
    }
  }
}
</style>
